import numpy as np
from sklearn.cluster import AgglomerativeClustering
import matplotlib.pyplot as plt

input_file = 'F:/python学习资料/Python-Machine-Learning-Cookbook-master/Chapter04/data_multivar.txt'
X = []
with open(input_file,'r') as f:
    for line in f.readlines():
        data = [float(x) for x in line.split(',')]
        X.append(data)

X = np.array(X)
print(X.shape)
print(X[:5])
plt.figure()
plt.scatter(X[:,0],X[:,1],facecolors='none',s=30,marker='o',edgecolors='k')
x_min,x_max = min(X[:,0])-1,max(X[:,0])+1
y_min,y_max = min(X[:,1])-1,max(X[:,1])+1
plt.xlim(x_min,x_max)
plt.ylim(y_min,y_max)
plt.xticks(())
plt.yticks(())
plt.show()
agg = AgglomerativeClustering(n_clusters=4)
agg.fit(X)
print(agg.labels_[:5])
labels=agg.labels_.reshape(-1,1)
c = np.hstack((X,labels)).astype(int)
# print(c[:15])

c0 = [x for x in c if x[2]==0]
c0 = np.array(c0)


c1 = [x for x in c if x[2]==1]
c1 = np.array(c1)

c2 = [x for x in c if x[2]==2]
c2 = np.array(c2)

c3 = [x for x in c if x[2]==3]
c3 = np.array(c3)
plt.figure()
plt.xlim(x_min,x_max)
plt.ylim(y_min,y_max)
plt.xticks(())
plt.yticks(())
marker=['o','x','^','.']
plt.scatter(c0[:,0],c0[:,1],marker=marker[0],s=30)
plt.scatter(c1[:,0],c1[:,1],marker=marker[1],s=30)
plt.scatter(c2[:,0],c2[:,1],marker=marker[2],s=30)
plt.scatter(c3[:,0],c3[:,1],marker=marker[3],s=30)
plt.show()
# for i in range(200):
#     plt.scatter(c[i,0],c[i,1],marker=marker[c[i,2]])
# plt.show()
print(c3[:12])